package com.ex.src.chap07;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.*;
class Ticket {
    private int count = 3;    // 售卖总票数
    private Lock lock = new ReentrantLock(); // 互斥锁
    public void sale() {
        this.lock.lock();    // 售票业务
        try {
            if (this.count > 0) {
                TimeUnit.SECONDS.sleep(1);    // 有剩余票数
                System.out.println(" ["+ Thread.currentThread().getName() + "] 卖票，剩余票数：" + this.count--);
            } else {
                System.err.println(" ["+ Thread.currentThread().getName() + "] 票已卖完了，明天再来！");
            }
        } catch (Exception e) {
        } finally {
            this.lock.unlock();    // 解除锁定
        }
    }
}

public class YookDemo {
    public static void main(String[] args) throws Exception {
        Ticket ticket = new Ticket();    // 对象实例化
        for (int x = 0; x < 5; x++) {
            new Thread(() -> {
                ticket.sale();    // 售票处理
            }, "售票员 - " + x).start();
        }
    }
}